package com.example.gokchinesefoodmappcdev.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

/**
 * 异常处理，如果发生异常，记录日志+跳转页面
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 错误处理
    @ExceptionHandler(Exception.class)
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> globalExceptionHandler(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e){
        // 1. 异常记录
        logger.error("===============================异常记录=========================");
        // 1.1 请求地址
        logger.error("完整请求地址 ：" + request.getRequestURL() + "?" + request.getQueryString());
        // 1.2 请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> strings = parameterMap.keySet();
        for (String string : strings) {
            logger.error("request提交参数key值：" + string + "   value值：" + parameterMap.get(string));
        }
        // 打印所有的异常堆栈信息
        logger.error(e.getMessage(), e);
        logger.error("====================================异常记录完毕==================================");

        // 2. 页面跳转
        return factory -> {
            // 出现403资源不可用
            ErrorPage forbidden = new ErrorPage(HttpStatus.FORBIDDEN, "error/403");
            // 出现404跳转页面找不到界面
            ErrorPage notFound = new ErrorPage(HttpStatus.NOT_FOUND, "error/404");
            // 出现500页面跳转
            ErrorPage sysError = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "error/500");
            factory.addErrorPages(forbidden, notFound, sysError);
        };
    }
}
